import Taro, { useDidShow, useReachBottom } from "@tarojs/taro";
import React, { useState, useReducer, useEffect } from "react";
import { View, Text } from "@tarojs/components";
import {
  AtButton,
  AtInput,
  AtTabs,
  AtTabsPane,
  AtModal,
  AtModalHeader,
  AtModalContent,
  AtModalAction,
  AtActivityIndicator,
  AtMessage
} from "taro-ui";
import "taro-ui/dist/style/components/tabs.scss";
import { wxLogin, getCategory, getArticleByCategory, getArticleByUser } from "./api";
import Card from "../../component/Card";
import NullState from "../../component/NullState";
import "taro-ui/dist/style/components/button.scss";
import "taro-ui/dist/style/components/input.scss";
import "taro-ui/dist/style/components/modal.scss";
import "taro-ui/dist/style/components/activity-indicator.scss";
import "taro-ui/dist/style/components/loading.scss";
import "taro-ui/dist/style/components/message.scss";
import css from "./index.module.less";

export default function Index() {
  function reducer(state, action) {
    if (action.type === "userInfo") {
      state = action.userInfo;
    }
    return state;
  }
  const [state, dispatch] = useReducer(reducer, null);
  const [articleData, setArticleData] = useState([]);
  const [userInfo, setUserInfo] = useState(null);
  const [category, setCategory] = useState([]);
  const [loadingArticles, setLoadingArticles] = useState(true);
  const [page, setPage] = useState(1);
  const [size, setSize] = useState(6);

  const [current, setCurrent] = useState(1);
  const [currentCategory, setCategoryCurrent] = useState(0);
  const tabList = [{ title: "关注" }, { title: "发现" }];
  const [concernArticles, setConcernArticles] = useState([]);
  const handleClick = (value) => {
    setCurrent(value);
    setLoadingArticles(true);
    getArticleByUser(state.uuid).then((res) => {
      if (res.code === 200) {
        setConcernArticles(res.data);
        setLoadingArticles(false);
      }
    })
  };
  // 滑动到底部加载数据
  useReachBottom(() => {
    if (current === 1) {
      const currentPage = page + 1;
      setPage(currentPage);
      getArticleByCategory(category[currentCategory].title, state.uuid, currentPage, size).then((res) => {
        if (res.code === 200) {
          setArticleData([...articleData, ...res.data]);
          setLoadingArticles(false);
        }
      });
    }
  })
  const handleCategoryClick = (value) => {
    setCategoryCurrent(value);
    const title = category[value].title;
    setLoadingArticles(true);
    // 每一次分类切换后文章数据置为空，page值为1,
    setArticleData([]);
    setPage(1);
    getArticleByCategory(title, state.uuid, 1, size).then((res) => {
      if (res.code === 200) {
        setArticleData([...res.data]);
        setLoadingArticles(false);
      }
    });
  };

  const detail = (uuid, liked) => {
    Taro.navigateTo({ url: `detail/index?uuid=${uuid}&liked=${liked}` });
  };
  const [open, setOpen] = useState(false);
  useDidShow(() => {
    console.log("show");
    setCategoryCurrent(0);
    Taro.getStorage({
      key: "userInfo",
      success: function (res) {
        dispatch({
          type: "userInfo",
          userInfo: res.data,
        });
        // getArticle(res.data.uuid, 1, 10);
        setLoadingArticles(true);
        getArticleByCategory("绘画", res.data.uuid, 1, size).then((res) => {
          console.log(page, size);
          if (res.code === 200) {
            setArticleData([...res.data]);
            setLoadingArticles(false);
          }
        });
        getCategory().then((res) => {
          if (res.code === 200) {
            const data = res.data;
            const newData = [];
            for (let i = 0; i < data.length; i++) {
              const element = data[i];
              newData.push({ title: element.title });
            }
            setCategory(newData);
          }
        });
        setOpen(false);
      },
      fail: function () {
        setOpen(true);
      },
    });
  });

  const login = () => {
    Taro.login({
      success: function (res) {
        console.log(res.code);
        wxLogin(`/login/wxLogin/${res.code}`).then((r) => {
          console.log(r);
          if (r.code === 200) {
            // 微信团队抛弃了wx.getUserInfo、wx.getUserProfile接口
            // 获取用户头像将统一返回默认灰色头像，昵称将统一返回 “微信用户”
            // Taro.getUserInfo({
            //   success: function (res) {
            //     console.log(res.userInfo);
            //   }
            // })
            Taro.setStorage({
              key: "userInfo",
              data: r.data,
            });
            dispatch({
              type: "userInfo",
              userInfo: r.data,
            });
            setCategoryCurrent(0);
            setLoadingArticles(true);
            getArticleByCategory("绘画", res.data.uuid, page, size).then((res) => {
              if (res.code === 200) {
                setArticleData([...res.data]);
                setLoadingArticles(false);
              }
            });
            setUserInfo(r.data);
            setOpen(false);
          }
        });
      },
    });
  };
  const confirm = (value) => {
    console.log(value);
    if (value === null || value === undefined || value === "") {
      Taro.atMessage({
        'message': '请输入搜索的信息',
        'type': "warning",
      })
    } else {
      Taro.navigateTo({ url: `search/index?value=${value}&uuid=${state.uuid}` });
    }

  }
  return (
    <React.Fragment>
      <View className={css.content}>
        <AtMessage />
        {/* <AtModal isOpened={open}>
          <AtModalHeader>登录</AtModalHeader>
          <AtModalContent>
            <Text style={{ textAlign: "center" }}>请使用微信登录</Text>
          </AtModalContent>
          <AtModalAction>
            {" "}
            <AtButton>取消</AtButton> <AtButton onClick={login}>确定</AtButton>{" "}
          </AtModalAction>
        </AtModal> */}
        <AtInput placeholder="搜索" onConfirm={confirm} className={css.search}/>
        <AtTabs current={current} tabList={tabList} onClick={handleClick}>
          <AtTabsPane current={current} index={0}>
          {loadingArticles ? (
          ""
        ) : concernArticles.length === 0 ? (
          <NullState />
        ) : (
          <View className={css.card}>
            {concernArticles.map((result) => {
              return (
                <View onClick={() => detail(result.article.uuid, result.liked)}>
                  <Card {...result} />
                </View>
              );
            })}
          </View>
        )}
          </AtTabsPane>

          <AtTabsPane current={current} index={1}>
            <AtTabs
              current={currentCategory}
              tabList={category}
              onClick={handleCategoryClick}
            >
              <AtActivityIndicator
                content="加载中..."
                isOpened={loadingArticles}
              ></AtActivityIndicator>
              {loadingArticles
                ? ""
                : category.map((r, i) => {
                    return (
                      <AtTabsPane current={currentCategory} index={i} key={i}>
                        <View>
                          <View className={css.card}>
                            {articleData.length === 0 ? (
                              <NullState />
                            ) : (
                              articleData.map((result) => {
                                return (
                                  <View
                                    onClick={() =>
                                      detail(result.article.uuid, result.liked)
                                    }
                                  >
                                    <Card {...result} />
                                  </View>
                                );
                              })
                            )}
                          </View>
                        </View>
                      </AtTabsPane>
                    );
                  })}
            </AtTabs>
          </AtTabsPane>
        </AtTabs>
      </View>
    </React.Fragment>
  );
}
